package simulator;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class Phrases {
	private int SESSION_NUM = 1;
	private int PHRASE_NUM = 10;
	private int cnt;
	private ArrayList<String> phraseList;
	
	/**constructor*/
	public Phrases() {
		phraseList = new ArrayList<>();
	}
	
	/**input phrases from inputFile*/
	public void input(String inputFile) {
		FileReader fr = null;
		try {
			fr = new FileReader(inputFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		BufferedReader br = new BufferedReader(fr);
		
		phraseList.clear();
		try {
			String line;
			while ((line = br.readLine()) != null) {
				line = line.toLowerCase();
				phraseList.add(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		for (int i = 1; i < phraseList.size(); i++) {
			int j = (int)(Math.random() * i);
			String tmp = phraseList.get(i);
			phraseList.set(i, phraseList.get(j));
			phraseList.set(j, tmp);
		}
	}
	
	/**get cnt*/
	public int getCnt() {
		return cnt;
	}
	
	public int getSession() {
		return cnt / PHRASE_NUM + 1;
	}
	
	public void setSessionNum(int sessionNum) {
		SESSION_NUM = sessionNum;
	}
	
	public void setPhraseNum(int phraseNum) {
		PHRASE_NUM = phraseNum;
	}
	
	public boolean sessionFinished() {
		return (cnt % PHRASE_NUM == 0);
	}
	
	public boolean experimentFinished() {
		return (cnt == SESSION_NUM * PHRASE_NUM);
	}
	
	/**pass current phrase(cnt++)*/
	public boolean passPhrase() {
		if (cnt < phraseList.size()) {
			cnt++;
			return true;
		}
		return false;
	}
	
	/**get current phrase(index = cnt)*/
	public String getPhrase() {
		if (cnt < phraseList.size())
			return phraseList.get(cnt);
		return "";
	}
	
	/**get current word according the inputed text*/
	public String getCurrentWord(String text) {
		int wordsInText = (text.length() == 0) ? 0 : 1;
		for (int i = 0; i < text.length(); i++) {
			if (text.charAt(i) == ' ')
				wordsInText++;
		}

		String phrase = getPhrase();
		int wordsInPhrase = (phrase.length() == 0) ? 0 : 1;
		for (int i = 0; i < phrase.length(); i++) {
			if (phrase.charAt(i) == ' ')
				wordsInPhrase++;
			if (wordsInPhrase == wordsInText + 1) {
				int st = (i == 0) ? 0 : i + 1;
				int len = 1;
				while (st + len < phrase.length() && phrase.charAt(st + len) != ' ')
					len++;
				
				String currentWord = phrase.substring(st, st + len);
				return currentWord;
			}
		}
		return "";
	}
}
